# Definition for a binary tree node.
# class TreeNode:
#     def __init__(self, x):
#         self.val = x
#         self.left = None
#         self.right = None

class Solution:
    def buildTree(self, inorder: List[int], postorder: List[int]) -> TreeNode:
        helporder=postorder[::-1]
        length=len(postorder)
        idx_map = {val:idx for idx, val in enumerate(inorder)} 
        def findsubtree(node,index,left,right):
            if right==index+1:
                node.right=None
            else:
                rightnode=TreeNode(postorder[-1])
                node.right=rightnode
                postorder.pop()
                findsubtree(rightnode,idx_map[rightnode.val],index+1,right)
            if left==index:
                node.left=None
            else:
                leftnode=TreeNode(postorder[-1])
                node.left=leftnode
                postorder.pop()
                findsubtree(leftnode,idx_map[leftnode.val],left,index)
        if length==0:
            return None
        root=TreeNode(postorder[-1])
        postorder.pop()
        findsubtree(root,inorder.index(root.val),0,length)
        return root